package com.example.mycarcalling.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.track.TraceOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.utils.DistanceUtil;
import com.example.lib_cache.model.Application;
import com.example.lib_cache.model.Guide;
import com.example.lib_cache.model.Order;
import com.example.lib_cache.model.User;
import com.example.lib_cache.service.ApiService;
import com.example.lib_cache.viewmodel.PickUpActivityViewModel;
import com.example.lib_cache.viewmodel.TravelActivityViewModel;
import com.example.lib_common.util.MarkMoveUtil;
import com.example.lib_common.util.MileageUtils;
import com.example.mycarcalling.R;
import com.example.mycarcalling.databinding.ActivityPickUpBinding;
import com.example.mycarcalling.databinding.ActivityTravelBinding;

import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class TravelActivity extends AppCompatActivity {

    private final static String TAG = TravelActivity.class.getSimpleName();

    private Context context = null;

    private ActivityTravelBinding activityTravelBinding = null;
    private TravelActivityViewModel travelActivityViewModel = null;

    private BaiduMap baiduMap = null;
    private TraceOptions traceOptions = null;

    private Timer requestTimer = null;

    private GetOffConfirmDialog getOffConfirmDialog = null;
    private BitmapDescriptor bitmap = null;
    private MarkerOptions markerOptions = null;
    private Marker marker = null;
    private MarkMoveUtil markMoveUtil = null;

    @Inject
    ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityTravelBinding = DataBindingUtil.setContentView(this,
                R.layout.activity_travel);
        context = this;
        initView();
        initData();
        initObserve();
        initRequest();
        initListener();
        initTimer();
    }

    private void initTimer() {

        //初始化定时器
        requestTimer = new Timer();
        Log.d(TAG,"5秒后开始执行：每6秒获取一次坐标数据");
        //5秒后开始执行：每6秒获取一次坐标数据
        requestTimer.schedule(new TimerTask() {
            public void run() {
                Log.d(TAG,"发起请求");
                travelActivityViewModel.requestDriverLocation(apiService,context);
            }
        }, 5000,6000);
    }

    private void initListener() {
        activityTravelBinding.btnConfirmTravel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"确认下车");
                getOffConfirmDialog.show();
            }
        });

        getOffConfirmDialog.getBtn_confirm().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG,"发送修改订单状态请求");
                travelActivityViewModel.requestGetOff(apiService,context);
            }
        });
    }

    private void initRequest() {

        travelActivityViewModel.requestNavigation(apiService,context);
        //仅加载时一次请求
        travelActivityViewModel.requestOrder(apiService,context);
    }

    private void initObserve() {

        travelActivityViewModel.getGuideMutableLiveData().observe(this, new Observer<Guide>() {
            @Override
            public void onChanged(Guide guide) {
                //更新轨迹UI
//                Log.d(TAG,"司机经度:"+guide.getGuiDriverLongitude());
//                Log.d(TAG,"司机纬度："+guide.getGuiDriverLatitude());


                //将司机位置加入经、纬度集合
                travelActivityViewModel.swapLatLng(
                        guide.getGuiDriverLongitude(),guide.getGuiDriverLatitude());
                Log.d(TAG,"olderll:"+travelActivityViewModel.getOrderLL().longitude+" "+travelActivityViewModel.getOrderLL().latitude);
                Log.d(TAG,"newll:"+travelActivityViewModel.getNewLL().longitude+" "+travelActivityViewModel.getNewLL().latitude);

                //至少设置两个坐标数据
                if(!travelActivityViewModel.getSwap()){
//                    自适应地图缩放视野
//                    设置缩放级别
                    //司机坐标
                    LatLng ll = new LatLng(guide.getGuiDriverLatitude(),
                            guide.getGuiDriverLongitude());
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll);
                    builder.zoom(20);
                    baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                    marker.setPosition(ll);
                    travelActivityViewModel.setSwap(true);
                }
                //设置车辆移动
                markMoveUtil.initLatlngData(
                        travelActivityViewModel.getOrderLL(),
                        travelActivityViewModel.getNewLL());
                markMoveUtil.moveLooper();
                //更新剩余里程距离
                activityTravelBinding.tvLeftMileageTravel
                        .setText("剩余里程："+
                                MileageUtils.meterToKilometers((int)DistanceUtil
                                .getDistance(new LatLng(
                                        travelActivityViewModel.getNavigationMutableLiveData().getValue()
                                                .getEndLatitude(),
                                        travelActivityViewModel.getNavigationMutableLiveData().getValue()
                                                .getEndLongitude()),
                                             new LatLng(guide.getGuiDriverLatitude(),
                                                        guide.getGuiDriverLongitude()))));



            }
        });

        travelActivityViewModel.getOrderMutableLiveData().observe(this, new Observer<Order>() {
            @Override
            public void onChanged(Order order) {
                Log.d(TAG,"用订单获取司机信息");
                travelActivityViewModel.requestPersonInfo(
                        apiService,context,order.getDeliveryDriver());

            }
        });

        travelActivityViewModel.getUserMutableLiveData().observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                travelActivityViewModel.requestApplication(apiService,context,user.getId());
            }
        });

        travelActivityViewModel.getApplicationMutableLiveData().observe(this, new Observer<Application>() {
            @Override
            public void onChanged(Application application) {
                activityTravelBinding.tvDriverNameTravel.setText(
                        travelActivityViewModel.getUserMutableLiveData().getValue().getNickname());
                activityTravelBinding.tvCarNumberTravel.setText(application.getLicensePlate());
                activityTravelBinding.tvCarModelTravel.setText(
                        application.getCarModel()+"-"+application.getColor()+"色");
                activityTravelBinding.tvPhoneTravel.setText(
                        travelActivityViewModel.getUserMutableLiveData().getValue().getPhoneNumber());
            }
        });

        travelActivityViewModel.getIsGetOff().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if(aBoolean){
                    Log.d(TAG,"本次约车结束");
                    travelActivityViewModel.saveNavToSettlement();
                    getOffConfirmDialog.dismiss();
                    setResult(1);
                    finish();
                }
            }
        });
    }

    private void initData() {
        //初始化动态轨迹
        traceOptions = new TraceOptions();
        traceOptions.animationTime(5000);
        traceOptions.animate(true);
        traceOptions.animationType(TraceOptions.TraceAnimateType.TraceOverlayAnimationEasingCurveLinear);
        traceOptions.color(0xAAFF0000);
        traceOptions.width(10);
    }

    private void initView() {
        setTitle("目的地导航");
        //创建数据源
        //创建一个ViewModel的工厂
        ViewModelProvider.Factory factory = ViewModelProvider.
                AndroidViewModelFactory.getInstance(getApplication());
        //创建ViewModel的管理对象
        ViewModelProvider viewModelProvider = new ViewModelProvider(this,factory);
        //生产ViewModel
        travelActivityViewModel = viewModelProvider.
                get(TravelActivityViewModel.class);


        //地图初始化
        baiduMap = activityTravelBinding.mapviewTravel.getMap();
        baiduMap.setTrafficEnabled(true);
        baiduMap.setMyLocationEnabled(true);

        //设置车辆图标
        bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_car);

        //初始化坐标参数
        LatLng latLng = baiduMap.getMapStatus().target;
        //准备 marker option 添加 marker 使用
        markerOptions = new MarkerOptions().icon(bitmap).position(latLng);
        //获取添加的 marker 这样便于后续的操作
        marker = (Marker) baiduMap.addOverlay(markerOptions);

        markMoveUtil = new MarkMoveUtil(
                1000,
                activityTravelBinding.mapviewTravel,
                marker,context);
        getOffConfirmDialog = new GetOffConfirmDialog(context);
    }

    @Override
    public void onResume() {
        activityTravelBinding.mapviewTravel.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        activityTravelBinding.mapviewTravel.onPause();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        baiduMap.setMyLocationEnabled(false);
        activityTravelBinding.mapviewTravel.onDestroy();
        requestTimer.cancel();
        super.onDestroy();
    }

    @Override
    public void onStop()
    {
        // 关闭图层定位
        baiduMap.setMyLocationEnabled(false);
        super.onStop();
    }
}